<?php
namespace App\Http\Controllers;

use App\Models\Organization;
use App\Http\C5\C5ResponseFactory;
use App\Models\Province;
use Illuminate\Support\Facades\DB;

class OrganizationController extends BaseController
{

    public function edit(){
        $id = $this->get("organization_id");
        //如有需要这里加上排重的功能
        if(empty($id)){
            return $this->create();
        }else{
            return $this->update();
        }
    }

    public function create()
    {
        $bean = new Organization();
        $this->markCreateInfo($bean);
        $bean->forceFill($this->request->all());
        $bean->save() ;
        return C5ResponseFactory::newSuccessInstance($bean);
    }

    public function update()
    {
        /**
        * @var  $bean Organization
        */
        $organization_id = $this->get("organization_id");
        $bean = Organization::find($organization_id);
        if (empty($bean)) {
            return C5ResponseFactory::newRecordNotExistsInstance();
        }
        $args = $this->request->all();
        $this->markUpdateInfo($bean);
        $bean->forceFill($args);
        $bean->update() ;
        return C5ResponseFactory::newSuccessInstance($bean);
    }

    public function delete()
    {
        /**
        * @var  $bean Organization
        */

        $organization_id = $this->get("organization_id");
        $bean = Organization::find($organization_id);
        if (empty($bean)) {
            return C5ResponseFactory::newSuccessInstance($organization_id);
        }
        // 检查数据完整性,如果有被使用就不可以删除

        // $object = SomeModel::where("organization_id", $organization_id)->first();
        // if (!empty($object)) {
        //      return C5ResponseFactory::newRecordUsedInstance();
        // }

        $bean->delete();
        // 删除关联的数据
        // SomeModel::on($db)->where("organization_id", $organization_id)->delete();

        return C5ResponseFactory::newSuccessInstance($organization_id);
    }

    public function detail(){
        $id = $this->get("organization_id");
        return $this->find($id);
    }

    public function find($organization_id)
    {
        $sql = "
            select a.*
            from organization a
            where organization_id=?
        ";
        $result = DB::select($sql,[$organization_id]);
        if(empty($result)){
            return C5ResponseFactory::newRecordNotExistsInstance();
        }
        return C5ResponseFactory::newSuccessInstance($result[0]);
    }

    public function grid()
    {
        $sql = "
            select a.* from organization a
            where 1=1
        ";
        $sql .= $this->getQueryLimits();
        $sql .= $this->getOrderBy(["organization_id"=>"desc"]);
        $result = $this->gridQuery($sql);
        return C5ResponseFactory::newSuccessInstance($result);
    }


}

